package com.yuhs.zixing.study.multithread.mashibing.t002lock.l003;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Function:
 *
 * @Author yuhongsheng
 * @Date: 2023-12-23 21:16:34
 */
@Slf4j
public class Lock003ReentrantLock002 {

    Lock lock = new ReentrantLock();


    @SneakyThrows
    public void m1() {
        try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                log.atInfo().log("m1方法执行 {}", i);
            }

        } finally {
            lock.unlock();
        }
    }

    @SneakyThrows
    public void m2() {
        boolean locked = false;
        try {
            locked = lock.tryLock(10, TimeUnit.SECONDS);
            log.atInfo().log("m2方法执行");
        } finally {
            if (locked) {
                lock.unlock();
            }
        }
        log.atInfo().log("尝试锁 结果 {}",locked);
    }

    @SneakyThrows
    public static void main(String[] args) {
        Lock003ReentrantLock002 reentrantLock001 = new Lock003ReentrantLock002();
        new Thread(reentrantLock001::m1).start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(reentrantLock001::m2).start();
    }

}
